package com.yicong.ants.scenic

import android.app.AlertDialog
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocation
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity
import com.yicong.ants.R
import com.yicong.ants.databinding.ScenicLocationFragmentBinding
import com.yicong.ants.scenic.adapter.CityAdapter
import com.yicong.ants.scenic.adapter.CityChildAdapter
import com.yicong.ants.scenic.data.CityInfo
import com.yicong.ants.scenic.viewModel.ScenicViewModel

class ScenicLocationFragment : Fragment() {
    private val viewMode: ScenicViewModel by activityViewModels()
    private val adapterNode = mutableMapOf<String, Int>()
    private lateinit var adapter: CityAdapter
    private val childAdapterNode = mutableMapOf<String, Int>()
    private lateinit var childAdapter: CityChildAdapter

    private lateinit var binding: ScenicLocationFragmentBinding
    private lateinit var locationPermissionLauncher: ActivityResultLauncher<String>
    val callback = object : LocationUtil.Callback {
        override fun onRequestPermission() {
            AlertDialog.Builder(requireActivity())
                .setView(R.layout.live_common_dialog)
                .show().apply {
                    findViewById<TextView>(R.id.messageTv).text =
                        "“游吧通”要获取你的地理位置 用于展示附近的景区信息以及您与景区的距离信息"
                    findViewById<TextView>(R.id.positiveBtn).setOnClickListener {
                        dismiss()
                        LocationUtil.requestPermission(locationPermissionLauncher)
                    }
                    findViewById<TextView>(R.id.negativeBtn).setOnClickListener {
                        dismiss()
                        ToastUtils.showLong("获取定位失败")
                        binding.txPositioning.text = "深圳"

                        binding.txPositioning.setOnClickListener {
                            viewMode.pCity.value = "广东"
                            viewMode.pChild.value = "深圳"
                            findNavController().navigateUp()
                        }
                    }
                    window?.setBackgroundDrawable(null)
                }
        }

        override fun onLocation(location: AMapLocation) {
            binding.txPositioning.text = location.city
            binding.txPositioning.setOnClickListener {
                viewMode.pLa = location.latitude.toString()
                viewMode.pLo = location.longitude.toString()
                viewMode.pCity.value = if (location.province.endsWith("省")) {
                    location.province.substring(0, location.province.length - 1)
                } else if (location.province.endsWith("市")) {
                    location.province.substring(0, location.province.length - 1)
                } else {
                    location.province
                }
                viewMode.pChild.value = if (location.city.endsWith("市")) location.city.substring(
                    0,
                    location.province.length - 1
                ) else location.city
                findNavController().navigateUp()
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        BarUtils.setStatusBarLightMode(requireActivity(), true)
        binding = ScenicLocationFragmentBinding.inflate(layoutInflater, container, false)
        binding.backBtn.setOnClickListener { findNavController().navigateUp() }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        locationPermissionLauncher =
            registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
                if (isGranted) {
                    LocationUtil.startLocateOnce(requireContext(), this, callback)
                } else {
                    ToastUtils.showLong("获取定位失败")

                    binding.txPositioning.text = "深圳"
                    binding.txPositioning.setOnClickListener {
                        viewMode.pCity.value = "广东"
                        viewMode.pChild.value = "深圳"
                        findNavController().navigateUp()
                    }
                }
            }

        LocationUtil.startLocateOnce(requireContext(), viewLifecycleOwner, callback)

        viewMode.cityList.observe(viewLifecycleOwner) { data1 ->
            data1?.let { data2 ->
                val list = data2.data
                list?.let {
                    adapterNode.clear()
                    var cityLetter = ""
                    for (i in 0 until it.size) {
                        if (cityLetter != it[i].initials) {
                            cityLetter = it[i].initials
                            list.add(
                                i,
                                CityInfo(id = "-1", name = cityLetter, initials = cityLetter, null)
                            )
                            adapterNode[cityLetter] = i
                        }
                    }

                    if (viewMode.pChild.value == null) {
                        viewMode.selectStatus = 0
                        binding.recycler.adapter = adapter
                        adapter.setNewData(it)
                    } else {
                        val cityPosition = viewMode.getCityPosition(viewMode.pCity.value!!)
                        if (cityPosition == -1) {
                            viewMode.selectStatus = 0
                            binding.recycler.adapter = adapter
                            adapter.setNewData(it)
                        } else {
                            adapter.selectPosition = cityPosition
                            viewMode.selectCity(viewMode.getChildInfo(viewMode.pCity.value!!)!!)
                            val childPosition = viewMode.getChildPosition(viewMode.pChild.value!!)
                            adapter.setNewData(it)
                            if (childPosition != -1) {
                                viewMode.child.value =
                                    viewMode.getChildData(viewMode.pChild.value!!)!!
                                childAdapter.selectPosition = childPosition
                            }
                        }
                    }
                }
            }
        }

        viewMode.childList.observe(viewLifecycleOwner) { list ->
            list?.let {
                var cityLetter = ""
                childAdapterNode.clear()
                for (i in 0 until it.size) {
                    if (cityLetter != it[i].initials) {
                        cityLetter = it[i].initials
                        list.add(
                            i,
                            CityInfo.ChildArea(
                                pid = "-1",
                                name = cityLetter,
                                id = "-1",
                                initials = cityLetter
                            )
                        )
                        childAdapterNode[cityLetter] = i
                    }
                }
                viewMode.selectStatus = 1
                binding.recycler.adapter = childAdapter
                childAdapter.setNewData(it)
            }
        }

        viewMode.city.observe(viewLifecycleOwner) {
            tipsLayoutAdd()
        }
        viewMode.child.observe(viewLifecycleOwner) {
            tipsLayoutAdd()
        }

        binding.sideBar.setOnTouchingLetterChangedListener {
            if (viewMode.selectStatus == 0) {
                if (adapterNode.containsKey(it)) {
                    (binding.recycler.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                        adapterNode[it]!!,
                        0
                    )
                }
            } else {
                if (childAdapterNode.containsKey(it)) {
                    (binding.recycler.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                        childAdapterNode[it]!!,
                        0
                    )
                }
            }
        }

        //刷新定位
        binding.refreshP.setOnClickListener {
            LocationUtil.startLocateOnce(requireContext(), viewLifecycleOwner, callback)
        }

        initRecycler()
        viewMode.getCityList(requireActivity() as BaseTitleBarActivity<*>)
    }

    private fun initRecycler() {
        adapter = CityAdapter()
        adapter.setOnItemClickListener { a, view, position ->
            if (a.getItemViewType(position) == 1) {
                viewMode.selectCity(adapter.getItem(position))

                val oldPosition = adapter.selectPosition
                adapter.selectPosition = position
                if (oldPosition != -1) {
                    adapter.notifyItemChanged(oldPosition)
                }
                adapter.selectPosition = position
                adapter.notifyItemChanged(adapter.selectPosition)
            }
        }

        childAdapter = CityChildAdapter()
        childAdapter.setOnItemClickListener { a, view, position ->
            if (a.getItemViewType(position) == 1) {
                viewMode.child.value = childAdapter.getItem(position)
                viewMode.pCity.value = viewMode.city.value?.name
                viewMode.pChild.value = viewMode.child.value?.name
                findNavController().navigateUp()
            }
        }

        val linearLayoutManager = LinearLayoutManager(requireContext())
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.recycler.layoutManager = linearLayoutManager
    }

    private fun tipsLayoutAdd() {
        val name = ArrayList<String>()
        viewMode.city.value?.let { city ->
            name.add(city.name)
            viewMode.child.value?.let {
                name.add(it.name)
            }
        }
        binding.tipsLayout.removeAllViews()
        for (i in 0 until name.size) {
            val view = LayoutInflater.from(requireContext()).inflate(R.layout.item_city_tips, null)
            view.tag = i
            view.setOnClickListener {
                if (it.tag as Int == 0 && viewMode.selectStatus != 0) {
                    viewMode.child.value = null
                    childAdapter.selectPosition = -1
                    viewMode.selectStatus = 0
                    binding.recycler.adapter = adapter
                }
            }
            val tipsView = view.findViewById<View>(R.id.ic_tips)
            val textView = view.findViewById<TextView>(R.id.name)
            textView.text = name[i]
            if (i == name.size - 1) {
                textView.typeface = Typeface.DEFAULT_BOLD
                tipsView.visibility = View.VISIBLE
            }
            val layoutParams = LinearLayout.LayoutParams(
                SizeUtils.dp2px(66f),
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            binding.tipsLayout.addView(view, layoutParams)
        }
    }
}